package com.lcc.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.lcc.common.to.es.SkuEsModel;
import com.lcc.gulimall.search.config.GulimallElasticSearchConfig;
import com.lcc.gulimall.search.constant.EsConstant;
import com.lcc.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient client;
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到es
        //1.给es中建立索引：product，建立好映射关系

        //2.给es中保存这些数据
        //批量操作
        BulkRequest bulkRequest = new BulkRequest();
        for(SkuEsModel model : skuEsModels){
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);//表示按照这个索引来存
            indexRequest.id(model.getSkuId().toString());//设置文档id
            String jsonString = JSON.toJSONString(model);//设置数据
            indexRequest.source(jsonString, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        //TODO 批量错误 处理
        if(bulk.hasFailures()){
            List<String> collect = Arrays.asList(bulk.getItems()).stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("商品上架错误：{}", collect);
            return false;
        }
        return true;
    }
}
